<!--
/**
* @author xuyh0817
* @email xuyh0817@foxmail.com
* @date 2022-02-19 00:00
* @version 2.0.0
* @doc todo
* @website todo
* @remark  如果要分发源码，需在本文件顶部保留此文件头信息！！
*/
-->
<template>
  <a-collapse v-bind="attrs">
    <template v-for="(item) in children">
      <a-collapse-panel :key="item.code" :header="item.name">
        <x-render-draggable
          active
          :current-id="xDesignForm.currentId"
          :form-data="xRenderForm.formData"
          :list="item.children"
          :component="xDesignForm.getComponent"
          @add="designAddHandler($event, item.children)"
          @end="designMoveEndHandler($event, item.children)"
          @copy="designCopyHandler"
          @remove="designRemoveHandler"
          @selected="designSelectedHandler"
          @data-change="dataChangeHandler($event,item)"
        >
        </x-render-draggable>
      </a-collapse-panel>
    </template>
  </a-collapse>
</template>

<script>
import { COMPONENT_TYPE, DESIGN_COMPONENT_SUFFIX } from '../../constants'
import XRenderComponentMixin from '../../XRenderMixins/XRenderComponentMixin'
import XRenderDesignMixin from '../../XRenderMixins/XRenderDesignMixin'
import { cloneDeep } from 'lodash'
import {getFormOption} from '../../utils'

export default {
  name: COMPONENT_TYPE.LAYOUT_COLLAPSE + DESIGN_COMPONENT_SUFFIX,
  mixins: [XRenderComponentMixin, XRenderDesignMixin],
  inject: ['xDesignForm'],
  computed: {
    children: {
      get() {
        const { attrs } = this
        return attrs.children || []
      }
    }
  },
  methods: {
    dataChangeHandler(list, child) {
      const { attrs, xDesignForm, id, isDebug } = this
      const formOption = getFormOption(xDesignForm.formOptions, id)
      if (!formOption) {
        isDebug ? console.warn('未找到表单项') : ''
        return
      }
      const attrsTmp = cloneDeep(attrs)
      const tabIndex = attrsTmp.children.findIndex(o => !!o.code && !!child.code && o.code === child.code)
      if (tabIndex !== -1) {
        child = cloneDeep(child)
        child.children = child.children || []
        child.children.splice(0, child.children.length, ...list)
        attrsTmp.children.splice(tabIndex, 1, child)
        this.$set(formOption, 'attrs', attrsTmp)
      }
    }
  }
}
</script>
